<?php

/**
 * 发送HTTP请求方法，目前只支持CURL发送请求
 * @param  string $url    请求URL
 * @param  array  $params 请求参数
 * @param  string $method 请求方法GET/POST
 * @return array  $data   响应数据
 */
function curlHttp($url, $params, $method = 'GET', $header = array(), $multi = false){
    $opts = array(
        CURLOPT_TIMEOUT        => 30,
        CURLOPT_RETURNTRANSFER => 1,
        CURLOPT_SSL_VERIFYPEER => false,
        CURLOPT_SSL_VERIFYHOST => false,
        CURLOPT_HTTPHEADER     => $header
    );

    /* 根据请求类型设置特定参数 */
    switch(strtoupper($method)){
        case 'GET':
            $opts[CURLOPT_URL] = $url . '?' . http_build_query($params);
            break;
        case 'POST':
            //判断是否传输文件
            $params = $multi ? $params : http_build_query($params);
            $opts[CURLOPT_URL] = $url;
            $opts[CURLOPT_POST] = 1;
            $opts[CURLOPT_POSTFIELDS] = $params;
            break;
        default:
            throw new Exception('不支持的请求方式！');
    }
    dump($opts);
    /* 初始化并执行curl请求 */
    $ch = curl_init();
    curl_setopt_array($ch, $opts);
    $data  = curl_exec($ch);
    $error = curl_error($ch);
    //$head = curl_getinfo($ch,CURLINFO_CONTENT_TYPE);
    curl_close($ch);
    if($error) throw new Exception('请求发生错误：' . $error);
    return  $data;
}

/*
 * 格式化金钱格式（传入数字，大于万的保留两位小数，小于万的不保留小数）
 * @param float $money 金额
 * @return float
 * */
function format_money($money, $flag = true)
{
    if ($money <= 0)
        return 0;
    switch ($money) {
        case $money < 10000:
            $money = sprintf("%01.2d", $money);
            break;
        case $money >= 10000:
            if ($flag == true) {
                $money = sprintf("%01.2f", $money / 10000) . '<i>万</i>';
            } else {
                $money = sprintf("%01.2f", $money / 10000) * 10000 . '<i>元</i>';
            }
            break;
        default:
            break;
    }
    return $money;
}

/**
 * 计算当前时间毫秒
 * @return float
 */
function ms_time() {
    list($usec, $sec) = explode(' ', microtime());
    return (float)sprintf('%.0d',(floatval($usec)+floatval($sec))*1000);
}

//计算交易服务费
/**
 * @param float $price 初始价格
 * @param string $starttime 场开始时间
 */
function get_commision($price,$starttime=''){
    $sysConfServ = new \ChannelThrift\Service\SystemConfService();

    $row = $sysConfServ->getConfByName('COMMISION_MIN_FEE');
    $arr = json_decode($row['remark'],true);
    if($arr['is_avalible']=='1'){
        if(date('Y-m-d',strtotime($starttime))==$arr['startdate']){
            $min_fee = $arr['commision'];
        }else{
            $min_fee = $row['value'];
        }
    }else{
        $min_fee = $row['value'];
    }
    $min_fee = intval($min_fee);

    $map = array();
    $map['name'] = array('in',array('COMMISION_MAX_FEE','COMMISION_PERCENTAGE'));
    $rows = $sysConfServ->getConfByMap($map);
    $config = array();
    foreach ($rows as $row) {
        $config[$row['name']] = $row['value'];
    }
    $max_fee = intval($config['COMMISION_MAX_FEE']);
    $percentage = floatval($config['COMMISION_PERCENTAGE']);

    $p = $price * $percentage;
    if ($p <= $min_fee) {
        $p = $min_fee;
    } elseif ($p >= $max_fee) {
        $p = $max_fee;
    } else {
        $p = round($p / 100) * 100;
    }
    return $p;
}

function test(){
    //echo 'hi,test().';
    $bailServ = new \ChannelThrift\Service\SystemConfService();
    $bail_info = $bailServ->getConfByName('COMMISION_MAX_FEE');
    $bail  = $bail_info['value'];
//    dump($bail);

}

//
/* 产生一个拍单编号
 * @param $type string 类型 car/order
 * @return string
 * */
function gen_order_no()
{
    $order = new \ChannelThrift\Service\OrderService();
    $map = array('create_time' => array('like', date('Y-m-d') . '%'));
    $o = $order->getOrderByMap($map);
    if ($o) {
        preg_match("/P" . date('ymd') . "([\d]{2,4})/", $o['order_no'], $matches);
        $no = sprintf("%04d", ($matches[1] + 1));
    } else {
        $no = '0001';
    }
    return 'P' . date('ymd') . $no;
}

/**
 * 抛出异常并记录日志
 * @param $code
 * @param string $message
 * @param array $argVals
 * @throws \Services\AuctionService\InvalidException
 */
function make_throw($code,$message='',$argVals=array()){
    $exceptionCode = C('EXCEPTION_CODE');
    $msg = !$message?$exceptionCode[$code]:$message;
    if($argVals){
        $pattern = [];
        preg_match_all('/#arg[0-9]+#/',$msg,$matches);
        if($matches[0]){
            foreach($matches[0] as $k=>$v){
                $pattern[] = '#arg'.$k.'#';
            }
        }
        $msg = str_ireplace($pattern,$argVals,$msg);
    }
    trace($msg, '', 'ERR',true);
    throw new \Services\AuctionService\InvalidException(array('code' => $code, 'message' => $msg));
}

/**
 *  通过Code获取Redis的Key
 *
 *  @param $configKey
 *  @param $code
 *  @param $dataArr
 *
 *  @return string
 */
function getRedisKeyByCode($configKey,$code,$dataArr=array()){
    $arr = C($configKey)[$code];
    $key = $arr['key'];
    foreach ($dataArr as $itemKey => $itemValue){
        $key = str_replace('#'.$itemKey.'#',$itemValue,$key);
    }
    return $key;
}

/**
 * 精确到毫秒
 *
 * @return int
 */
function microtime_time()
{
    list($sec, $micro) = explode(" ", microtime());
    return ceil(((float)$sec + (float)$micro) * 1000);
}

//计算到0点的剩余时间（秒）
function time_left_to_24(){
    $stime = strtotime(date('Y-m-d 23:59:59'));
    $time = $stime - time();
    return $time;
}
